package com.quyunshuo.module.home.manager

import android.content.Context
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import com.quyunshuo.module.home.fragment.home.HomeRepository
import com.quyunshuo.module.home.room.dao.AppUsageDao
import com.quyunshuo.module.home.room.entity.AppUsageEntity
import com.tencent.bugly.Bugly.applicationContext
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit

class AppUsageWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted workerParams: WorkerParameters,
    private val repository: HomeRepository,
    private val appUsageDao: AppUsageDao
) : CoroutineWorker(context, workerParams) {

    override suspend fun doWork(): Result {
        return try {
            // 1. 获取应用使用数据
            val days = inputData.getInt(KEY_DAYS, DEFAULT_DAYS)
            val appUsages = withContext(Dispatchers.IO) {
                repository.getAppUsageStats(applicationContext, days)
            }
            
            // 2. 转换为实体并保存到数据库
            val entities = appUsages.map { usage ->
                AppUsageEntity(
                    packageName = usage.packageName,
                    appName = usage.appName,
                    duration = usage.duration,
                    lastTimeUsed = usage.lastTimeUsed
                )
            }
            
            appUsageDao.insertAll(entities)
            
            // 3. 清理旧数据（保留最近30天的记录）
            val cutoffTime = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30)
            appUsageDao.deleteOldRecords(cutoffTime)
            
            // 4. 记录成功信息
            val successMessage = "成功记录 ${entities.size} 个应用的使用数据"
            Result.success(Data.Builder().putString(KEY_RESULT, successMessage).build())
        } catch (e: Exception) {
            // 记录错误信息
            Result.failure(Data.Builder().putString(KEY_ERROR, e.message).build())
        }
    }

    companion object {
        const val KEY_DAYS = "days"
        const val KEY_RESULT = "result"
        const val KEY_ERROR = "error"
        const val DEFAULT_DAYS = 1
        
        // 创建定期任务
        fun schedulePeriodicWork(context: Context, days: Int = DEFAULT_DAYS) {
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
                .setRequiresBatteryNotLow(true)
                .setRequiresStorageNotLow(true)
                .build()

            val workRequest = PeriodicWorkRequestBuilder<AppUsageWorker>(
                15, TimeUnit.MINUTES // 每15分钟执行一次
            ).setConstraints(constraints)
             .setInputData(Data.Builder().putInt(KEY_DAYS, days).build())
             .build()

            WorkManager.getInstance(context).enqueueUniquePeriodicWork(
                "AppUsageWorker",
                ExistingPeriodicWorkPolicy.UPDATE, // 更新现有任务
                workRequest
            )
        }
    }

    /*
      // 开启WorkManager
    private fun startWorker() {
        kotlin.runCatching {
            val constraints = Constraints.Builder()
                .setRequiredNetworkType(NetworkType.NOT_REQUIRED)  // 不需要网络连接
                .setRequiresBatteryNotLow(false)                // 电池不低
                .setRequiresCharging(false)                    // 不需要充电
                .setRequiresDeviceIdle(false)// 不需要设备空闲
                .setRequiresStorageNotLow(false)                // 存储空间不低
                .build()

            val workRequest = PeriodicWorkRequestBuilder<StepWorker>(15, TimeUnit.MINUTES)
                .setConstraints(constraints)  // 设置约束条件
                .setBackoffCriteria(                    // 重试策略
                    BackoffPolicy.LINEAR,               // 线性重试
                    MIN_BACKOFF_MILLIS,
                    TimeUnit.MILLISECONDS
                )
                .build()
            WorkManager.getInstance(this)
                .enqueueUniquePeriodicWork(
                    "step_worker_run",
                    ExistingPeriodicWorkPolicy.KEEP,
                    workRequest
                )
        }
     */
}

/*
class StepWorker(context: Context, workerParams: WorkerParameters) :
    CoroutineWorker(context, workerParams) {

    private var initStep: Long? = null
    override suspend fun doWork(): Result {
        return try {
            YoLog.d("StepWorker", "doWork")
            // 无谷歌步数服务
            if (RecordingAPIonMobileManager.hasMinPlayServices().not()) {
                RebootStepEmitter.register()
                RebootStepEmitter.rebootStepFlow.value?.let {
                    if (initStep == null) {
                        initStep = it
                    } else {
                        val dStep = it - initStep!!
                        YoLog.d("StepWorker", "dStep: $dStep")
                        StepViewModel.addStepsToday(dStep.toInt())
                    }
                    initStep = it
                }
            }
            Result.success()
        } catch (e: Exception) {
            Result.failure()
        }
    }

}
 */